//
//  ChangePhoneView.m
//  suRead
//
//  Created by 龚浩植 on 16/4/27.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "ChangePhoneView.h"
#import "ServiceUser.h"
#import "UIViewController+HUD.h"
#import "AccountManager.h"

#import "AppDelegate.h"
#import "UIApplication+VisibleViewController.h"
#import "LoginViewController.h"
#import "HomeTabBarController.h"
#import "ModalViewController.h"
@interface ChangePhoneView()

@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;

@property (weak, nonatomic) IBOutlet UIView *bgView;

@end
@implementation ChangePhoneView

+ (instancetype)changePhoneView
{
    ChangePhoneView *changePhoneView = [[[NSBundle mainBundle] loadNibNamed:@"ChangePhoneView" owner:self options:nil] lastObject];
    
    return changePhoneView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)awakeFromNib
{
    self.contentView.layer.masksToBounds = YES;
    self.contentView.layer.cornerRadius  = 10;
    self.contentView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
    self.contentView.layer.borderWidth = 1.0f;
    [self.getCodeButton addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    
    _phoneText.delegate = self;
    _codeText.delegate = self;
    _pwdText.delegate = self;
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
//                                                 name:UIKeyboardWillShowNotification object:self.contentView.window];
    
////    if (weka_self.iskeybord) {
//        [self.phoneText resignFirstResponder];
//        [self.codeText resignFirstResponder];
//        [self.pwdText resignFirstResponder];
////        weka_self.iskeybord = NO;
////    }

}
//
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    if  ([textField isFirstResponder]  && self.bgView.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    if (![textField isFirstResponder] && self.bgView.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }

    
}


//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    [textField resignFirstResponder];

    return YES;
}


-(void)setViewMovedUp:(BOOL)movedUp
{
//    [UIView beginAnimations:nil context:NULL];
   // [UIView setAnimationDuration:0.5]; // if you want to slide up the view
    int kOFFSET_FOR_KEYBOARD = 90;
    CGRect rect = self.bgView.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.bgView.frame = rect;
    
   // [UIView commitAnimations];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    if (![textField isFirstResponder] && self.bgView.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
    
//    self.contentView.frame =CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
}

//- (void)setTitle:(NSString *)title
//{
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTap:)];
//    [self.bgView addGestureRecognizer:tap];
//    self.bgView.userInteractionEnabled = YES;
//
//}


- (void)getCode:(id)sender
{
    __weak typeof(self) weak_self = self;
//
//    self.getCodeButton.userInteractionEnabled=NO;
//    self.getCodeButton.alpha=0.4;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        weak_self.getCodeButton.userInteractionEnabled=YES;
//        weak_self.getCodeButton.alpha=1.0f;
//    });
 
    if(!(self.phoneText.text.length>0 && [self validateNumber:self.phoneText.text] && self.phoneText.text.length==11)){
         [[[[UIApplication sharedApplication] keyWindow] rootViewController] showHUDText:@"请输入手机号"];
        return;
    }
    [self startTime];
    
    [[[[UIApplication sharedApplication] keyWindow] rootViewController] showHUDProgress:nil];
    
    [ServiceUser doGetPhoneCode:self.phoneText.text
                        success:^(id responseObject, NSString *message) {
                            [[[[UIApplication sharedApplication] keyWindow] rootViewController] removeHUDProgress];
                            [[[[UIApplication sharedApplication] keyWindow] rootViewController] showHUDText:message];
                            
                        } failure:^(NSString *message) {
                            [[[[UIApplication sharedApplication] keyWindow] rootViewController] removeHUDProgress];
                            [[[[UIApplication sharedApplication] keyWindow] rootViewController] showHUDText:message];
//                            weak_self.getCodeButton.userInteractionEnabled=YES;
//                            weak_self.getCodeButton.alpha=1.0f;
                        }];
    
}

-(void)startTime{
    
    __block int timeout= 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
    
                //设置界面的按钮显示 根据自己需求设置
                
                [self.getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                
                self.getCodeButton.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = timeout % 60;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [UIView beginAnimations:nil context:nil];
                
                [UIView setAnimationDuration:1];
                
                [self.getCodeButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                
                [UIView commitAnimations];
                
                self.getCodeButton.userInteractionEnabled = NO;
                
            });
            
            timeout--;
  
        }
    });
    
    dispatch_resume(_timer);

    
}


- (void)viewTap:(id)sender
{
    if (self.baViewTapCallBackBlock) {
        self.baViewTapCallBackBlock();
    }
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
@end
